package org.yuanqiframework.yuanqi.core.utils.dict;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DictUtils {

    public static class KeyLabel {
        private String group;
        private String key;
        private String label;

        public String getGroup() {
            return group;
        }

        public void setGroup(String group) {
            this.group = group;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }
    }

    public static class Item {


        private String group;
        private final List<KeyLabel> list = new LinkedList<>();

        public Item put(String key, String value) {
            KeyLabel keyLabel = new KeyLabel();
            keyLabel.setGroup(group);
            keyLabel.setKey(key);
            keyLabel.setLabel(value);
            list.add(keyLabel);
            return this;
        }

        public String getGroup() {
            return group;
        }

        public void setGroup(String group) {
            this.group = group;
        }

        public List<KeyLabel> getList() {
            return list;
        }
    }

    private static final Map<String, Item> map = new ConcurrentHashMap<>();


    public static synchronized Item group(String key) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
        Item item = new Item();
        item.setGroup(key);
        map.put(key, item);
        return item;
    }

    public static List<KeyLabel> listAll() {
        List<KeyLabel> list = new LinkedList<>();
        for (String key : map.keySet()) {
            List<KeyLabel> keyLabels = get(key);
            if (keyLabels != null) {
                list.addAll(keyLabels);
            }
        }
        return list;
    }


    public static List<KeyLabel> get(String group) {
        Item item = map.get(group);
        if (item != null) {
            return item.getList();
        } else {
            return null;
        }
    }


    public static KeyLabel get(String group, String key) {
        List<KeyLabel> list = get(group);
        if (list == null) {
            return null;
        }
        return list.stream()
                .filter(keyLabel -> keyLabel.getKey().equals(key))
                .findFirst()
                .orElse(null);
    }

    public static void clear() {
        map.clear();
    }
}
